<?php
/*
$json_errors = array(
    JSON_ERROR_NONE => 'No error has occurred',
    JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
    JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
    JSON_ERROR_SYNTAX => 'Syntax error',
);

function saveError($errno, $errstr, $error_line) {
	file_put_contents ("{$_SERVER["DOCUMENT_ROOT"]}/modules/menu/error_log.txt","Error: $errstr\n Line: $error_line\n", FILE_APPEND );
}

//set error handler
set_error_handler("saveError");

$config_module = "{$_SERVER["DOCUMENT_ROOT"]}/modules/config/index.php";
include "$config_module";

$base64_menu = base64_decode($_REQUEST["json_menu"]);
$json_menu = json_decode($base64_menu,true);
$menu_string = serialize ($json_menu);

$base64_navbar = base64_decode($_REQUEST["json_navbar"]);
$json_navbar  = json_decode($base64_navbar,true,1000);
$navbar_string = serialize ($json_navbar);

//Catch version 0.01 file structure
if (is_dir("{$_SERVER["DOCUMENT_ROOT"]}/modules/menu")) { 
	chdir("{$_SERVER["DOCUMENT_ROOT"]}/modules/menu");
	//file_put_contents ("pending_menu.txt",$menu_string);
	//file_put_contents ("pending_navbar.txt",$navbar_string);
	
	file_put_contents ("pending_menu.json",$json_menu);
	file_put_contents ("pending_navbar.json",$json_navbar);
	
	
	
	
	file_put_contents ("{$_SERVER["DOCUMENT_ROOT"]}/modules/menu/error_log.txt","{$_REQUEST["json_menu"]}\n\r\n\r", FILE_APPEND );
	file_put_contents ("{$_SERVER["DOCUMENT_ROOT"]}/modules/menu/error_log.txt","{$base64_navbar}\n\r\n\r", FILE_APPEND );
	file_put_contents ("{$_SERVER["DOCUMENT_ROOT"]}/modules/menu/error_log.txt","{$json_navbar}\n\r\n\r", FILE_APPEND );
	file_put_contents ("{$_SERVER["DOCUMENT_ROOT"]}/modules/menu/error_log.txt","{$navbar_string}\n\r\n\r", FILE_APPEND );
	
	file_put_contents ("{$_SERVER["DOCUMENT_ROOT"]}/modules/menu/error_log.txt",$json_errors[json_last_error()], FILE_APPEND );
}

//Catch new structure
/*
if (isset($config["template"]) && (is_dir("{$_SERVER["DOCUMENT_ROOT"]}/modules/templates/{$config["template"]}/menu"))) {
	chdir("{$_SERVER["DOCUMENT_ROOT"]}/modules/templates/${config["template"]}/menu");
	file_put_contents ("pending_menu.txt",$menu_string);
	file_put_contents ("pending_navbar.txt",$navbar_string);
}
*/
/*
echo "saved";
*/

chdir("{$_SERVER["DOCUMENT_ROOT"]}/modules/menu");


$base64_menu = base64_decode($_REQUEST["json_menu"]);
$json_menu = json_decode($base64_menu,true);
file_put_contents("pending_menu.json",json_encode ($json_menu));

$base64_navbar = base64_decode($_REQUEST["json_navbar"]);
$json_navbar  = json_decode($base64_navbar,true,1000);
file_put_contents("pending_navbar.json",json_encode ($json_navbar));



echo "saved";


?>
